#include "syntaxTree.h"


struct TreeNode *
tree_node_new(const char* name, t_kind kind) {
    int i;
    struct TreeNode *node;

    node = (struct TreeNode *) malloc (sizeof(struct TreeNode));

    if (name != NULL) {
        node->name = strdup(name);
    } else
        node->name = NULL;

    node->kind = kind;
    //node->type = VOID;
    node->child_counter = 0;   
    node->parent = NULL;
    node->children = NULL;
    node->sibling = NULL;

    return node;
}

/*-----------------------------------------------------------------*/


void
tree_node_add_child(struct TreeNode *self, struct TreeNode *child)
{
    struct TreeNode *temp;

    if (child == NULL)
        return;

    if (self->children == NULL) {
        child->parent = self;
        self->children = child;
    } else {
        tree_node_add_sibling(self->children, child);
    }
    for (temp = child; temp != NULL; temp = temp->sibling)
        temp->parent = self;
}

void

/*-----------------------------------------------------------------*/


tree_node_add_sibling(struct TreeNode *self, struct TreeNode *sibling)
{
    struct TreeNode *temp = self;

    if (sibling == NULL)
        return;

    if (self->sibling == NULL) {
        self->sibling = sibling;
        sibling->parent = self->parent;
    } else {
		while(temp->sibling != NULL){
			temp = temp->sibling;
		}
        temp->sibling = sibling;
        sibling->parent = self->parent;

    }
}

/*-----------------------------------------------------------------*/


void printTree(TreeNode *root) {
	if (root == NULL)
			return;
	printf("node: %s\n",root->name);
	printTree(root->children);
	if(root->sibling != NULL)
	{
		printTree(root->sibling);
	}
}

/*-----------------------------------------------------------------*/

void tree_node_accept(TreeNode *self, Visitor *visitor) {
	if (self == NULL) {
        return;
	}
    //self->child_counter = 1;
    visitor->visitorFunction[self->kind](visitor, self);
}

/*-----------------------------------------------------------------*/


void tree_node_accept_children(TreeNode *self, Visitor *visitor)
{
    TreeNode *temp = self;
    while (temp != NULL) {
        tree_node_accept(temp, visitor);
        temp = temp->sibling;
	}
}

/*-----------------------------------------------------------------*/
